#include "CSU8RP3216.h"
#include "stdint.h"
#include "DevicesDelay.h"
#include "DevicesBlower.h"
#include "DevicesPower.h"



static SoftTimerTypeDef g_typeTimerBlower = {0};
static SoftTimerTypeDef g_typeTimerCharge = {0};



void vPowerInit(void)
{
    /*
        PT 数据标志位
    */
    PT1_4 = 0;

    /*
        PT5EN 输入/输出控制标志
        0: 定义为输入口
        1: 定义为输出口
    */
    PT1EN_4 = 1;

    /*
        PT5PU 上拉电阻使能标志
        0: 断开上拉电阻
        1: 使用上拉电阻
    */
    PT1PU_4 = 0;

    POWER_CHARGE_DISABLE();

    /* x 分钟内，只集尘1次 */
    cSoftTimerSetS(&g_typeTimerBlower, 60 * 10, softTimerOpen);
    cSoftTimerSetState(&g_typeTimerBlower, softTimerOver);

    /* 涓流充电 x 分钟 */
    cSoftTimerSetS(&g_typeTimerCharge, 60 * 2, softTimerOpen);
}

void vPowerMachine(void)
{
#define POWER_IDLE      0
#define POWER_START     1
#define POWER_CHARGEING 2
#define POWER_STOP      3


    static uint8_t g_ucPowerMachineState = POWER_IDLE;
    extern int32_t g_iVoltage;    /* mV */
    extern int32_t g_iCurrent;    /* mA */

    switch(g_ucPowerMachineState)
    {
        case POWER_IDLE:
            BLOWER_STOP();
            POWER_CHARGE_DISABLE();
            /* 上座后，电压会被拉低到4V左右 */
            if((g_iVoltage > 1000) && (g_iVoltage < 4500))
            {
                g_ucPowerMachineState = POWER_START;
            }
            break;

        case POWER_START:
            /* 每 x 秒内，只正常集尘1次 */
            if(enumSoftTimerGetState(&g_typeTimerBlower) == softTimerOver)
            {
                cSoftTimerReset(&g_typeTimerBlower);
                BLOWER_START();
            }
            /* 开启充电使能后，电压会被拉低到1.5V左右 */
            POWER_CHARGE_ENABLE();
            g_ucPowerMachineState = POWER_CHARGEING;
            break;

        case POWER_CHARGEING:
            /* 电压异常 */
            if((g_iVoltage < 1000)
            /* 过流 */
            || (g_iCurrent > 1000))
            {
                /* 没有集尘满 x 秒就退出，刚下次继续集尘 */
                if(enumSoftTimerGetState(&g_typeTimerBlower) != softTimerOver)
                {
                    cSoftTimerSetState(&g_typeTimerBlower, softTimerOver);
                }
                g_ucPowerMachineState = POWER_IDLE;
            }

            /* 已充满，电压会回升 */
            if((g_iVoltage > 3500)
            /* 已充满，电流会小于100mA */
            || (g_iCurrent < 100))
            {
                /* x 分钟涓流计时开始 */
                cSoftTimerReset(&g_typeTimerCharge);
                g_ucPowerMachineState = POWER_STOP;
            }
            break;

        case POWER_STOP:
            /* x 分钟涓流计时 */
            if(enumSoftTimerGetState(&g_typeTimerCharge) == softTimerOver)
            {
                g_ucPowerMachineState = POWER_IDLE;
            }
            break;

        default : g_ucPowerMachineState = POWER_IDLE; break;
    }
}
